#include "curvedialog.h"
#include "ui_curvedialog.h"

#include <QRegularExpressionValidator>
#include <QRegularExpression>

#include <QTimer>
#include <QDebug>

#include <QScreen>

CurveDialog::CurveDialog(const QStringList curveNames, QMap<QString, QWidget*> *tabWidget, QWidget *parent)
    : QDialog(parent)
    , m_curveNames(curveNames)
    , m_tabWidget(tabWidget)
    , ui(new Ui::CurveDialog)
{
    ui->setupUi(this);

    // setWidgetHide(true);

    // 创建正则表达式，这里以3位数字为例
    QRegularExpression regExp("^[0-9]{3}$"); // 限制为3位数字
    QRegularExpressionValidator *validator = new QRegularExpressionValidator(regExp, ui->cbox_data_interval);
    ui->cbox_data_interval->lineEdit()->setValidator(validator);

    // 下拉框默认初始化
    ui->cbox_monitoring->addItems(m_curveNames);
    // resetPageBox();
    // resetChartBox();
    ui->cbox_data_interval->addItem(QString("10"));
    ui->cbox_data_interval->addItem(QString("20"));
    ui->cbox_data_interval->addItem(QString("30"));
    ui->cbox_data_interval->addItem(QString("40"));
    ui->cbox_data_interval->addItem(QString("50"));
    ui->cbox_data_interval->addItem(QString("100"));
    ui->cbox_data_interval->addItem(QString("200"));
    ui->cbox_data_interval->addItem(QString("300"));
    ui->cbox_data_interval->addItem(QString("400"));
    ui->cbox_data_interval->addItem(QString("500"));
    ui->cbox_data_interval->addItem(QString("1000"));
    ui->cbox_data_interval->setCurrentText(QString("100"));

    on_cbox_monitoring_activated(0);
    setWidgetHide(false);

    // 延迟执行 centerWindow，确保窗口尺寸已计算完毕
    // QTimer::singleShot(10, this, &CurveDialog::centerWindow);
    // 使用lambda表达式来延迟调用 centerWindow
    QTimer::singleShot(100, this, [this](){ centerWindow(this); });
}

CurveDialog::~CurveDialog()
{
    delete ui;
}

void CurveDialog::showEvent(QShowEvent *event)
{
    // 在窗口显示时调用居中函数
    // centerWindow(this);

    // 调用基类的 showEvent 以确保其他处理可以继续进行
    QDialog::showEvent(event);
}

void CurveDialog::centerWindow(QWidget *window)
{
    // 获取当前屏幕对象
    QScreen *screen = QApplication::primaryScreen();
    if (screen) {
        QRect screenGeometry = screen->availableGeometry();
        int screenWidth = screenGeometry.width();
        int screenHeight = screenGeometry.height();

        // 获取窗口的尺寸
        int windowWidth = window->width();
        int windowHeight = window->height();

//        qDebug() << "windowWidth:" << windowWidth << " " << "windowHeight:" << windowHeight;

        // 计算窗口的左上角坐标，使窗口居中
        int x = (screenWidth - windowWidth) / 2;
        int y = (screenHeight - windowHeight) / 2;

//        qDebug() << "x:" << x << " " << "y:" << y;

        // 设置窗口的位置
        window->move(x, y);
    }
}

void CurveDialog::setWidgetHide(bool isHide)
{
    if(isHide)
    {
        // 隐藏输入框
        ui->ledit_place_chart_name->hide();
        ui->ledit_place_page_name->hide();
    } else {
        // 显示输入框
        ui->ledit_place_chart_name->show();
        ui->ledit_place_page_name->show();
    }
}


void CurveDialog::resetPageBox()
{
    ui->cbox_place_page->clear();
    ui->cbox_place_page->addItem("");
    ui->cbox_place_page->setItemText(0, QString("添加新页面 ->"));
    ui->ledit_place_page_name->setPlaceholderText(QString("请输入新的页面名"));
}

void CurveDialog::resetChartBox()
{
    ui->cbox_place_chart->clear();
    ui->cbox_place_chart->addItem("");
    ui->cbox_place_chart->setItemText(0, QString("添加新页面 ->"));
    ui->ledit_place_chart_name->setPlaceholderText(QString("请输入新的页面名"));
}


void CurveDialog::on_btn_ok_clicked()
{
    QString tabWidgetName = ui->ledit_place_page_name->text().trimmed();
    if(tabWidgetName.isEmpty())
    {
        qDebug() << "tabWidgetName not is Empty.";
        return;
    }

    QString chartWidgetName = ui->ledit_place_chart_name->text().trimmed();
    if(chartWidgetName.isEmpty())
    {
        qDebug() << "chartWidgetName not is Empty.";
        return;
    }
    QString dataInterval = ui->cbox_data_interval->currentText().trimmed();

    QString curveName = ui->cbox_monitoring->currentText().trimmed();

    // add map data
    QMap<QString, QString> dataMap;
    dataMap.insert("tabName", tabWidgetName);
    dataMap.insert("chartName", chartWidgetName);
    dataMap.insert("curveName", curveName);
    dataMap.insert("dataInterval", dataInterval);

    // send signal
    emit sendAddTabWidgetData(dataMap);

    this->accept();
}


void CurveDialog::on_cbox_monitoring_activated(int index)
{
    Q_UNUSED(index)

    // 重置下拉框信息
    resetPageBox();
    resetChartBox();

    // 更新下拉框信息
    updateCboxData(ui->cbox_place_page, m_tabWidget->keys());
}


void CurveDialog::on_cbox_place_page_activated(int index)
{
    Q_UNUSED(index)

    QString currentText = ui->cbox_place_page->currentText().trimmed();

    resetChartBox();    // 重置曲线下拉框

    if(currentText != ui->cbox_place_page->itemText(0))
    {
        ui->ledit_place_page_name->setText(currentText);
        ui->ledit_place_page_name->setEnabled(false);
        ui->ledit_place_page_name->hide();
    } else {
        ui->ledit_place_page_name->clear();

        ui->cbox_place_chart->setCurrentIndex(0);
        on_cbox_place_chart_activated(0);
        ui->ledit_place_page_name->setEnabled(true);
        ui->ledit_place_page_name->show();
    }


#if 0
    // 获取窗口
    MyWidgetLayout *widgetPlots = m_tabWidget->value(currentText);

    // 遍历
    if(widgetPlots != nullptr)
    {
        QMap<QString, MyWidgetPlot *> chartsMap = widgetPlots->getCharts();

        updateCboxData(ui->cbox_place_chart, chartsMap.keys());

    }
#endif
}

void CurveDialog::on_cbox_place_chart_activated(int index)
{
    QString currentText = ui->cbox_place_chart->currentText();



#if 0
    if(currentText != ui->cbox_place_chart->itemText(0))
    {
        QString currentTabText = ui->cbox_place_page->currentText();
        MyWidgetLayout *widgetLayout = m_tabWidget->value(currentTabText);

        qDebug() << "widgetLayout:" << widgetLayout << " " << (widgetLayout != nullptr);

        MyWidgetPlot *widgetPlot = widgetLayout->getCharts().value(currentText);

        qDebug() << "widgetPlot:" << widgetPlot << " " << (widgetPlot != nullptr);
        QString interval = QString::number(widgetPlot->intervalTime());
        ui->cbox_data_interval->setCurrentText(interval);

        ui->ledit_place_chart_name->setText(currentText);
        ui->ledit_place_chart_name->setEnabled(false);
        ui->ledit_place_chart_name->hide();
    } else {
        ui->ledit_place_chart_name->clear();
        ui->ledit_place_chart_name->setEnabled(true);
        ui->ledit_place_chart_name->show();
    }
#endif
}


void CurveDialog::updateCboxData(QComboBox *comboBox, const QList<QString> &tabs)
{
    QSet<QString> existingKeys;

    // 获取 `ui->cbox_place_page` 中已存在的选项
    for (int i = 0; i < comboBox->count(); ++i) {
        existingKeys.insert(comboBox->itemText(i));
    }

    // 遍历并添加不重复的选项
    for (const QString &key : tabs) {
        if (!existingKeys.contains(key)) {
            comboBox->addItem(key);
        }
    }
}


void CurveDialog::on_ledit_place_page_name_editingFinished()
{
    QString pageName = ui->ledit_place_page_name->text().trimmed();

    // 遍历下拉框，查询pageName是否已存在，调整对应的下拉框
    int index = ui->cbox_place_page->findText(pageName);    // 获取pageName对应的索引
    if(index == -1) {
        return; // 没找到，不做任何处理
    } 
    ui->cbox_place_page->setCurrentIndex(index);
    on_cbox_place_page_activated(index);
}

